#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>

static void usage(const std::string &proc)
{
    std::cout << std::endl
              << "Usage: " << proc << " ip port" << std::endl
              << std::endl;
}

// 服务端的字典服务实现的是短服务 即为一个客户端服务一次后 该服务停止 客户端再次申请服务时必须再次socket/connect

// ./tcp_client targetIp targetPort
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        usage(argv[0]);
        exit(1);
    }
    std::string serverIp = argv[1];
    uint16_t serverPort = atoi(argv[2]);

    int socketFd = 0;
    std::string line;
    char buf[1024];

    while (true)
    {
        socketFd = socket(AF_INET, SOCK_STREAM, 0);
        if (socketFd < 0)
        {
            std::cerr << "socket error" << std::endl;
            return 2;
        }

        // client 不需要显示的bind 他肯定是需要port
        // client的port让os自动选择 从而有连接别人的能力
        struct sockaddr_in dst_sockAddr;
        memset(&dst_sockAddr, 0, sizeof(dst_sockAddr));
        dst_sockAddr.sin_family = AF_INET;
        dst_sockAddr.sin_addr.s_addr = inet_addr(serverIp.c_str());
        dst_sockAddr.sin_port = htons(serverPort);

        if (connect(socketFd, (struct sockaddr *)&dst_sockAddr, sizeof(dst_sockAddr)) < 0)
        {
            std::cerr << "connect error" << std::endl;
            close(socketFd); // 关闭文件描述符以避免资源泄露
            return 3;
        }
        std::cout << "connect success" << std::endl;

        std::cout << "请输入# ";
        std::cin >> std::ws; // 跳过前导空白字符
        std::getline(std::cin, line);
        if (line == "quit")
        {
            close(socketFd);
            break;
        }

        ssize_t sendBytes = send(socketFd, line.c_str(), line.size(), 0);
        if (sendBytes < 0)
        {
            std::cerr << "send error!" << std::endl;

            close(socketFd);
            continue;
        }
        memset(buf, 0, sizeof buf);
        ssize_t recvBytes = recv(socketFd, buf, sizeof(buf) - 1, 0); // typedef ssize_t long int
        if (recvBytes > 0)
        {
            buf[recvBytes] = 0;
            std::cout << "server echo# " << buf << std::endl;
        }
        else if (recvBytes == 0)
        {
            // 服务器主动关闭连接
            std::cout << "Server closed connection" << std::endl;
        }
        else
        {
            std::cerr << "recv error!" << std::endl;
        }
        close(socketFd);
    }

    return 0;
}